﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria;
using Terraria.GameContent;
using Terraria.UI;

namespace HardcoreGame.Common.UI
{
    public class UIHealthBar : UIElement
    {
        private float _health = 1f;
        public Color BarColor = Color.LimeGreen;
        private Color _backgroundColor = new(50, 50, 50);
        private Color _borderColor = new(80, 80, 80);

        public void SetHealth(float health)
        {
            _health = MathHelper.Clamp(health, 0f, 1f);
        }

        protected override void DrawSelf(SpriteBatch spriteBatch)
        {
            CalculatedStyle dimensions = GetDimensions();
            spriteBatch.Draw(TextureAssets.MagicPixel.Value, new Rectangle((int)dimensions.X, (int)dimensions.Y, (int)dimensions.Width, (int)dimensions.Height), _backgroundColor);
            spriteBatch.Draw(TextureAssets.MagicPixel.Value, new Rectangle((int)dimensions.X, (int)dimensions.Y, (int)(dimensions.Width * _health), (int)dimensions.Height), BarColor);
            spriteBatch.Draw(TextureAssets.MagicPixel.Value, new Rectangle((int)dimensions.X - 1, (int)dimensions.Y - 1, (int)dimensions.Width + 2, 1), _borderColor);
            spriteBatch.Draw(TextureAssets.MagicPixel.Value, new Rectangle((int)dimensions.X - 1, (int)dimensions.Y + (int)dimensions.Height, (int)dimensions.Width + 2, 1), _borderColor);
            spriteBatch.Draw(TextureAssets.MagicPixel.Value, new Rectangle((int)dimensions.X - 1, (int)dimensions.Y, 1, (int)dimensions.Height), _borderColor);
            spriteBatch.Draw(TextureAssets.MagicPixel.Value, new Rectangle((int)dimensions.X + (int)dimensions.Width, (int)dimensions.Y, 1, (int)dimensions.Height), _borderColor);
            string text = $"{_health * 100:0}%";
            Vector2 textSize = FontAssets.MouseText.Value.MeasureString(text);
            Vector2 textPos = new(dimensions.X + dimensions.Width - textSize.X - 5, dimensions.Y + (dimensions.Height - textSize.Y) / 2);
            Utils.DrawBorderStringFourWay(spriteBatch, FontAssets.MouseText.Value, text, textPos.X, textPos.Y, Color.White, Color.Black, Vector2.Zero);
        }
    }
}